package com.worldcup.service.question.impl;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.worldcup.dao.question.QuestionOptionMapper;
import com.worldcup.model.question.Question;
import com.worldcup.model.question.QuestionOption;
import com.worldcup.service.question.QuestionOptionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * todo 加缓存
 * @author duwan.zq
 * @date 2019/03/05
 */
@Service
public class QuestionOptionServiceImpl implements QuestionOptionService {

    private final static Logger logger = LoggerFactory.getLogger(QuestionOptionServiceImpl.class);

    private LoadingCache<Long, Map<String, QuestionOption>> optionCache;

    @PostConstruct
    public void init(){
        optionCache = CacheBuilder.newBuilder().maximumSize(30).build(
            new CacheLoader<Long, Map<String, QuestionOption>>() {
                @Override
                public Map<String, QuestionOption> load(Long questionId){
                    List<QuestionOption> optionList = getOptionList(questionId);
                    Map<String, QuestionOption> map = new HashMap<>((int)(optionList.size() / 0.75));
                    optionList.forEach(option -> map.put(option.getOptionNo(), option));
                    return map;
                }
            });
    }

    @Autowired
    private QuestionOptionMapper questionOptionMapper;

    @Override
    public List<QuestionOption> getOptionList(long questionId){
        return questionOptionMapper.selectByQuestionId(questionId);
    }

    @Override
    public QuestionOption getOption(Long questionId, String optionNo) {
        Map<String, QuestionOption> optionMap = optionCache.getUnchecked(questionId);
        return optionMap.get(optionNo);
    }



}
